/*
* @(#)MaintDmsEmailDocumentAction.java
*
* Copyright (c) 2003 DCIVision Ltd
* All rights reserved.
*
* This software is the confidential and proprietary information of DCIVision
* Ltd ("Confidential Information").  You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the license
* agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.dms.web;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;

import com.dcivision.dms.DmsOperationConstant;
import com.dcivision.dms.EmailAuditTrailConstant;
import com.dcivision.dms.bean.DmsContent;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.DmsDocumentDetail;
import com.dcivision.dms.bean.DmsEmailAuditTrail;
import com.dcivision.dms.bean.DmsVersion;
import com.dcivision.dms.core.DocumentOperationManager;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.dms.dao.DmsDocumentDAObject;
import com.dcivision.dms.dao.DmsEmailAuditTrailDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.HTTPUtility;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.UserInfoFactory;
import com.dcivision.framework.Utility;
import com.dcivision.framework.bean.GenericAddress;
import com.dcivision.framework.notification.EmailDeliveryMessage;
import com.dcivision.framework.notification.NotificationWay;
import com.dcivision.framework.notification.NotificationWayFactory;
import com.dcivision.framework.web.AbstractActionForm;

/**
  MaintDmsEmailDocumentAction.java

  This class is for maint dms email dmsDocument action

    @author          Jenny Li
    @company         DCIVision Limited
    @creation date   06/08/2005
    @version         $Revision: 1.21.2.3 $
 */

public class MaintDmsEmailDocumentAction extends MaintDmsDocumentAction {

  public static final String REVISION = "$Revision: 1.21.2.3 $";

  protected String sListName = null;

  public MaintDmsEmailDocumentAction() {
    super();
    sListName = "dmsEmailDocumentList";
  }

  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  public String getMajorDAOClassName() {
    return("com.dcivision.dms.dao.DmsDocumentDAObject");
  }

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  public String getFunctionCode() {
    return(SystemFunctionConstant.DMS_PERSONAL_FOLDER);
  }
  
  /**
   * insertRecord - Override the parent function.
   *
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @return
   * @throws ServletException
   */
  public void insertRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    MaintDmsEmailDocumentForm documentForm = (MaintDmsEmailDocumentForm) form;
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DmsDocument newDocument = null;
    List attchList = new ArrayList();
    InputStream  inputStreamForAttchment = null;
    EmailDeliveryMessage msg = new EmailDeliveryMessage();
    EmailDeliveryMessage msgSend = new EmailDeliveryMessage();
   try{
	   String curUserEmail = UserInfoFactory.getUserEmailAddress(sessionContainer.getUserRecordID());
	    if (Utility.isEmpty(curUserEmail)) {
	      curUserEmail = SystemParameterFactory.getSystemParameter(SystemParameterConstant.SMTP_ADMIN_ADDRESS);
	    }
	    String curUserName = UserInfoFactory.getUserFullName(sessionContainer.getUserRecordID());
	    if (Utility.isEmpty(curUserName)) {
	      curUserName = SystemParameterFactory.getSystemParameter(SystemParameterConstant.SMTP_ADMIN_NAME);
	    }
	    msg.setSender(new GenericAddress("", curUserName,"utf-8"));
	    msgSend.setSender(new GenericAddress("", curUserName,"utf-8"));


	    String[] toRecipients = TextUtility.splitString(documentForm.getMailTo(), ";");
	    for (int i = 0; i < toRecipients.length; ++i) {
	      msg.addToRecipient(new GenericAddress(toRecipients[i]));
	      msgSend.addToRecipient(new GenericAddress(toRecipients[i]));
	    }
	    if (!Utility.isEmpty(documentForm.getMailCCTo())) {
	      String[] ccRecipients = TextUtility.splitString(documentForm.getMailCCTo(), ";");
	      for (int i = 0; i < ccRecipients.length; ++i) {
	        msg.addCCRecipient(new GenericAddress(ccRecipients[i]));
	        msgSend.addCCRecipient(new GenericAddress(ccRecipients[i]));
	      }
	    }
	   
	    msg.setCharset(SystemParameterFactory.getSystemParameter(SystemParameterConstant.ENCODING));
	    msg.setSubject(documentForm.getDocumentName());
	    msg.setMailContent(documentForm.getMailContent());
	    msgSend.setCharset(SystemParameterFactory.getSystemParameter(SystemParameterConstant.ENCODING));
	    msgSend.setSubject(documentForm.getDocumentName());
	    msgSend.setMailContent(documentForm.getMailContent());
	    int fileNameLength = TextUtility.parseInteger(SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_MAX_UPLOAD_FILENAME_LENGTH));        
	    String subjectStr = "";
	    
	    DocumentOperationManager documentOperationManager = new DocumentOperationManager(sessionContainer, conn);
	    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
	    InputStream inputStream=null;
	    
	    DmsDocument dmsDocument = (DmsDocument)documentForm.getFormData();
	    dmsDocument.setOwnerID(sessionContainer.getUserRecordID());
	    dmsDocument.setParentID(TextUtility.parseIntegerObj(documentForm.getParentID()));
	    dmsDocument.setRootID(TextUtility.parseIntegerObj(documentForm.getRootID()));
      
	    subjectStr = documentForm.getDocumentName();
	    TextUtility.stringValidation(subjectStr);
	    if(subjectStr.length() > fileNameLength){          
	      subjectStr = subjectStr.substring(0,fileNameLength-5);
	    }
	    
	    dmsDocument.setDocumentName(TextUtility.replaceInvalidChar(subjectStr," ")+".html");        
	    dmsDocument.setDocumentType(DmsDocument.EMAIL_DOC_TYPE);
	    dmsDocument.setCreateType(DmsOperationConstant.DMS_CREATE_BY_SYSTEM);
	    dmsDocument.setItemStatus(DmsVersion.AVAILABLE_STATUS);
	    dmsDocument.setItemSize(new Integer(documentForm.getMailContent().length()));
	    dmsDocument.setRecordStatus(GlobalConstant.RECORD_STATUS_ACTIVE);

	    try{
	      inputStream = new DataInputStream(new ByteArrayInputStream(documentForm.getMailContent().getBytes("UTF-8")));
	    }catch(Exception e){
	      log.error(e);
	    }
	    List detailList = new ArrayList();
	    String emailUDFProfileID = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_PROFILE_EMAIL_ID);
	    String emailUDFMailFromID = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_PROFILE_EMAIL_DETAIL_MAILFROM_ID);
	    String emailUDFMailToID = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_PROFILE_EMAIL_DETAIL_MAILTO_ID);
	    String emailUDFCCToID = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_PROFILE_EMAIL_DETAIL_CCTO_ID);
	    String emailUDFSubjectID = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_PROFILE_EMAIL_DETAIL_SUBJECT_ID);
	    String emailUDFSendDateID = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_PROFILE_EMAIL_DETAIL_MAILSENDDATE_ID);
	    
	    if (!Utility.isEmpty(emailUDFProfileID)) {
	      Integer emailUDFProfileIDInt = new Integer(emailUDFProfileID);
	      if (!Utility.isEmpty(emailUDFMailFromID)) {
	        DmsDocumentDetail docDetail = new DmsDocumentDetail();
	        docDetail.setRecordStatus(GlobalConstant.RECORD_STATUS_ACTIVE);
	        docDetail.setFieldValue(sessionContainer.getUserFullName());
	        docDetail.setUserDefinedFieldDetailID(new Integer(emailUDFMailFromID));
	        docDetail.setUserDefinedFieldID(emailUDFProfileIDInt);
	        detailList.add(docDetail);
	      }
	      
	      if (!Utility.isEmpty(emailUDFMailToID)) {
	        DmsDocumentDetail docDetail = new DmsDocumentDetail();
	        docDetail.setRecordStatus(GlobalConstant.RECORD_STATUS_ACTIVE);
	        docDetail.setFieldValue(documentForm.getMailTo());
	        docDetail.setUserDefinedFieldDetailID(new Integer(emailUDFMailToID));
	        docDetail.setUserDefinedFieldID(emailUDFProfileIDInt);
	        detailList.add(docDetail);
	      }
	      
	      if (!Utility.isEmpty(emailUDFCCToID)) {
	        DmsDocumentDetail docDetail = new DmsDocumentDetail();
	        docDetail.setRecordStatus(GlobalConstant.RECORD_STATUS_ACTIVE);
	        docDetail.setFieldValue(documentForm.getMailCCTo());
	        docDetail.setUserDefinedFieldDetailID(new Integer(emailUDFCCToID));
	        docDetail.setUserDefinedFieldID(emailUDFProfileIDInt);
	        detailList.add(docDetail);
	      }
	      
	      if (!Utility.isEmpty(emailUDFSubjectID)) {
	        DmsDocumentDetail docDetail = new DmsDocumentDetail();
	        docDetail.setRecordStatus(GlobalConstant.RECORD_STATUS_ACTIVE);
	        docDetail.setFieldValue(documentForm.getDocumentName());
	        docDetail.setUserDefinedFieldDetailID(new Integer(emailUDFSubjectID));
	        docDetail.setUserDefinedFieldID(emailUDFProfileIDInt);
	        detailList.add(docDetail);
	      }
	      
	      if (!Utility.isEmpty(emailUDFSendDateID)) {
	        DmsDocumentDetail docDetail = new DmsDocumentDetail();
	        docDetail.setRecordStatus(GlobalConstant.RECORD_STATUS_ACTIVE);
	        docDetail.setDateValue(Utility.getCurrentTimestamp());
	        docDetail.setFieldValue(Utility.getCurrentTimestamp().toString());
	        docDetail.setUserDefinedFieldDetailID(new Integer(emailUDFSendDateID));
	        docDetail.setUserDefinedFieldID(emailUDFProfileIDInt);
	        detailList.add(docDetail);
	      }
	    }
	    
	    dmsDocument.setDocumentDetails(detailList);
	    dmsDocument.setCreatePhysicalFile(false);
      
       dmsDocument.setItemSize(new Integer(inputStream==null? 0 : inputStream.available()));
	   newDocument = documentOperationManager.createDocument(dmsDocument, inputStream);
	   documentForm.setID(newDocument.getID().toString());
	   
	   InputStream attchInputStream = null;
	   InputStream attchIs = null;
	   if(!Utility.isEmpty(documentForm.getDmsFileNames())){
	      String[] fileNames=TextUtility.splitString(documentForm.getDmsFileNames(),"|");
	      for(int i=0;i<fileNames.length;i++){
	        String docID=fileNames[i].substring(fileNames[i].indexOf("["),fileNames[i].indexOf(":"));
	        docID=docID.substring(docID.indexOf("[")+1,docID.indexOf("]"));
	        DmsVersion dmsVersion = docRetrievalManager.getVersionByVersionID(TextUtility.parseIntegerObj(docID));
	        DmsDocument subDocument=docRetrievalManager.getDocument(dmsVersion.getDocumentID());
	        String subName = subDocument.getDocumentName().substring(0,subDocument.getDocumentName().lastIndexOf("."));
	        String ext = subDocument.getDocumentName().substring(subDocument.getDocumentName().lastIndexOf("."));
	        subDocument.setDocumentName(subName+"-V"+dmsVersion.getVersionNumber()+ext);
            DmsContent dmsContent = docRetrievalManager.getContentByContentID(dmsVersion.getContentID());
            StringBuffer folderpath = docRetrievalManager.getFoldersDirectories(subDocument);
            String segmentNo = Utility.isEmpty(dmsContent.getSegmentNO())? "" : "Document" + "/" + "segment" + dmsContent.getSegmentNO() + "/";
            folderpath.append(segmentNo);
            folderpath.append(dmsContent.getConvertedName());
            InputStream dmsInputStream = null;
            File dmsfile = new File(folderpath.toString());
            try{
            	dmsInputStream = new FileInputStream(dmsfile);
            }catch(Exception e){ }
            subDocument.setParentID(newDocument.getID());
	        if(!Utility.isEmpty(dmsInputStream)){
	        	subDocument=documentOperationManager.createDocument(subDocument,dmsInputStream);
	        }
	        if(!Utility.isEmpty(dmsInputStream)){
	        	dmsInputStream.close();
	        }
	        DmsVersion signVersion = docRetrievalManager.getTopVersionByDocumentID(subDocument.getID());  
	        DmsContent signContent = docRetrievalManager.getContentByContentID(signVersion.getContentID());
	        StringBuffer folderDir = docRetrievalManager.getFoldersDirectories(subDocument);
	        String segmentNoPath = Utility.isEmpty(signContent.getSegmentNO())? "" : "Document" + "/" + "segment" + signContent.getSegmentNO() + "/";
	        folderDir.append(segmentNoPath);
	        folderDir.append(signContent.getConvertedName());
	        
	        attchInputStream = new FileInputStream(dmsfile);
	        attchIs = new FileInputStream(dmsfile);
	        msg.addAttachment(subDocument.getDocumentName(),attchInputStream);
	        msgSend.addAttachment(subDocument.getDocumentName(),attchIs);
	        String locationPath =  docRetrievalManager.getLocationPath(subDocument.getParentID());
	        attchList.add(locationPath+"\\"+subDocument.getDocumentName()+";");
	      }
	    }
	    
	    /********************************************************************
	     * author:taohuaqing
	     * modify date: 2006-4-10;
	     * description: save Email type archive for attchment files; 
	     *******************************************************************/
	    InputStream sendMainAttch = null;
	    InputStream mainAttch = null;
	    if(documentForm.getDisplayFileNames()!=null){
	    	DmsDocument attchmentDmsDocument = new DmsDocument();
	    	String fileName = documentForm.getFileNames();
	        String storage_root = SystemParameterFactory.getSystemParameter(SystemParameterConstant.WORKFLOW_ATTACHMENT_PHYSICAL_PATH);
	        HttpSession session = request.getSession();
	 	    String sessionID = session.getId();
	 	    String filepath = storage_root+"/"+sessionID+"/";
	    	String[] fileNames = TextUtility.splitString(fileName,"|");
	    	String [] pathForSendEmail = new String[fileNames.length];
	    	for(int i=1; i<fileNames.length; i++){
 	    	  String secondValue = fileNames[i];
  	    	String[] secondSplit = TextUtility.splitString(secondValue,":");
  	    	String fileEnd = secondSplit[1];
  	    	String newFilepath = filepath + fileEnd;
  	    	pathForSendEmail[i] = filepath;
           
    	    try{
    	    	File files = new File(newFilepath); 
          
    	    	if(!files.exists()){
    	    	  log.error("file not find");
    	    	}
    	    inputStreamForAttchment = new FileInputStream(files);
            sendMainAttch = new FileInputStream(files);
            mainAttch = new FileInputStream(files);
    	    }catch(Exception e)
    	    {
            log.error(e, e);
    	    }
    	    attchmentDmsDocument.setParentID(newDocument.getID());
    	    attchmentDmsDocument.setCreateType(newDocument.getCreateType());
    	    attchmentDmsDocument.setRecordStatus(GlobalConstant.RECORD_STATUS_ACTIVE);
      		attchmentDmsDocument.setDocumentName(secondSplit[0]);
      		attchmentDmsDocument.setRootID(TextUtility.parseIntegerObj(documentForm.getRootID()));
      		attchmentDmsDocument.setDocumentType(newDocument.getDocumentType());
            attchmentDmsDocument.setItemSize(new Integer(inputStreamForAttchment.available()));
      		attchmentDmsDocument = documentOperationManager.createDocument(attchmentDmsDocument,inputStreamForAttchment);
      		msg.addAttachment(attchmentDmsDocument.getDocumentName(), sendMainAttch);
      		msgSend.addAttachment(attchmentDmsDocument.getDocumentName(), mainAttch);
      		attchList.add(docRetrievalManager.getLocationPath(newDocument.getID())+"\\" + attchmentDmsDocument.getDocumentName()+";");
	    	}
	    }
	   	
	    String contentType=HTTPUtility.getContentType(documentForm.getDocumentName());
	    msg.setContentType(contentType);
	    msgSend.setContentType(contentType);
	    
	    // save email origin file
	    String path = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_CACHEFOLDER_PATH);
	    File catcheFolder = new File(path);
	    if (!catcheFolder.exists()) {
	       catcheFolder.mkdir();
	    }
 	    String baseDir = path + "/" + subjectStr+ ".eml";
 	    File file = new File(baseDir);
 	    InputStream is = null;
 	    //InputStream oriInputStream = null;
	    try{
	    	MimeMessage message = (MimeMessage)msg.getResolvedMessage();
	 	    OutputStream os = new FileOutputStream(file);
	 	    message.writeTo(os);
	 	    message.saveChanges();
	 	    os.close();
	 	    is = new FileInputStream(file);
	 	   // oriInputStream = new FileInputStream(file);
	 	    DmsDocument oriDmsDocument = new DmsDocument();
	 	    oriDmsDocument.setParentID(newDocument.getID());
	 	    oriDmsDocument.setCreateType(newDocument.getCreateType());
	 	    oriDmsDocument.setRecordStatus(GlobalConstant.RECORD_STATUS_ACTIVE);
	 	    oriDmsDocument.setDocumentName(subjectStr+ ".eml");
	 	    oriDmsDocument.setRootID(TextUtility.parseIntegerObj(documentForm.getRootID()));
	 	    oriDmsDocument.setDocumentType(newDocument.getDocumentType());
	 	    oriDmsDocument.setPriority(GlobalConstant.PRIORITY_MEDIUM);
	 	    oriDmsDocument.setItemSize(new Integer(is.available()));
   	 	    oriDmsDocument.setDocumentType(DmsDocument.DOCUMENT_TYPE);
	 	    oriDmsDocument.setItemStatus(DmsVersion.AVAILABLE_STATUS);
	 	    oriDmsDocument = documentOperationManager.createDocument(oriDmsDocument,is);
	   		is.close();
	   		file.delete();
	    }catch(Exception e){
        log.error(e, e);
	    }
	    
       // send email    
	    NotificationWay emailNotification = NotificationWayFactory.getNotificationInstance(NotificationWay.EMAIL_NOTIFICATION_INSTANCE);
	    emailNotification.addDeliveryMessage(msgSend);
	   
	    emailNotification.send();	    
	    
	    
	    if(!Utility.isEmpty(attchInputStream)){
	      attchInputStream.close();
	      attchIs.close();
	    }
	    if(!Utility.isEmpty(sendMainAttch)){
	    	sendMainAttch.close();	
	    	mainAttch.close();
		}
	    log.debug("---------------Message Send Successfully--------------------");
	    
//	  add Email Audit Trail Record
	    DmsEmailAuditTrail dmsEmailAuditTrail = new DmsEmailAuditTrail();
	    dmsEmailAuditTrail.setEmailTo(documentForm.getMailTo().replaceAll(";"," ; "));
	    dmsEmailAuditTrail.setEmailFrom(UserInfoFactory.getUserEmailAddress(sessionContainer.getUserRecordID()));
	    dmsEmailAuditTrail.setEmailCc(documentForm.getMailCCTo().replaceAll(";"," ; "));
	    dmsEmailAuditTrail.setEmailBcc("");
	    dmsEmailAuditTrail.setUserid(sessionContainer.getUserRecordID());
	    dmsEmailAuditTrail.setEmailSubject(documentForm.getDocumentName());
	    dmsEmailAuditTrail.setOperation(EmailAuditTrailConstant.OPERATION_EMAIL_DOCUMENT);
	    dmsEmailAuditTrail.setEmailType(EmailAuditTrailConstant.EMAIL_TYPE_OUTBOUND);
	    dmsEmailAuditTrail.setSentDate(Utility.getCurrentTimestamp().toString());
	    dmsEmailAuditTrail.setAttchCount(new Integer(attchList.size()));
	    Iterator iter = attchList.iterator();
	    StringBuffer sb = new StringBuffer();
	    while(iter.hasNext()){
	    	String attchName = (String)iter.next();
	    	sb.append(attchName);
	    }
	    dmsEmailAuditTrail.setAttchName(sb.toString());
	    dmsEmailAuditTrail.setAttchSource("DMS");
	    dmsEmailAuditTrail.setRecordStatus(GlobalConstant.RECORD_STATUS_ACTIVE);
	    dmsEmailAuditTrail.setCreatorID(sessionContainer.getUserRecordID());
	    dmsEmailAuditTrail.setCreateDate(Utility.getCurrentTimestamp());
	    dmsEmailAuditTrail.setUpdateCount(new Integer(0));
	    dmsEmailAuditTrail.setUpdaterID(sessionContainer.getUserRecordID());
	    dmsEmailAuditTrail.setUpdateDate(Utility.getCurrentTimestamp());
	    DmsEmailAuditTrailDAObject emailDAO = new DmsEmailAuditTrailDAObject(sessionContainer,conn);
	    dmsEmailAuditTrail = (DmsEmailAuditTrail)emailDAO.insertObject(dmsEmailAuditTrail);
	    conn.commit();
	    docRetrievalManager.release();
	    documentForm.setFormData(newDocument);
	    documentForm.setDocumentName(subjectStr);
	    
   }catch(Exception e){
     log.error(e, e);
   }
    
  }
  
  public void selectRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    MaintDmsEmailDocumentForm maintForm = (MaintDmsEmailDocumentForm)form;
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    
    DmsDocument dmsDocument=docRetrievalManager.getDocument(TextUtility.parseIntegerObj(maintForm.getID()));
    maintForm.setFormData(dmsDocument);
    
    List docDetailList=docRetrievalManager.getDocumentDetailList(dmsDocument.getID());
    String emailUDFMailToID = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_PROFILE_EMAIL_DETAIL_MAILTO_ID);
    String emailUDFCCToID = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_PROFILE_EMAIL_DETAIL_CCTO_ID);
    String emailUDFProfileID = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_PROFILE_EMAIL_ID);
    String emailUDFMailFromID = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_PROFILE_EMAIL_DETAIL_MAILFROM_ID);
    String emailUDFSubjectID = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_PROFILE_EMAIL_DETAIL_SUBJECT_ID);
    String emailUDFSendDateID = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_PROFILE_EMAIL_DETAIL_MAILSENDDATE_ID);    
    
    
    for(int i=0;i<docDetailList.size();i++){
      DmsDocumentDetail docDetail=(DmsDocumentDetail)docDetailList.get(i);
      if(emailUDFMailToID.equals(docDetail.getUserDefinedFieldDetailID().toString())){
        maintForm.setMailTo(docDetail.getFieldValue());
      }else if(emailUDFCCToID.equals(docDetail.getUserDefinedFieldDetailID().toString())){
        maintForm.setMailCCTo(docDetail.getFieldValue());
      }else if(emailUDFSubjectID.equals(docDetail.getUserDefinedFieldDetailID().toString())){
        maintForm.setDocumentName(docDetail.getFieldValue());
      }else if(emailUDFSendDateID.equals(docDetail.getUserDefinedFieldDetailID().toString())){
        maintForm.setSendDate(docDetail.getFieldValue());
      }else if(emailUDFMailFromID.equals(docDetail.getUserDefinedFieldDetailID().toString())){
        maintForm.setMailSendFrom(docDetail.getFieldValue());
      }      
    }
    List attachmentList= docRetrievalManager.getDocumentListByParentIDRootID(dmsDocument.getID(),dmsDocument.getRootID());
    String path = docRetrievalManager.getLocationPath(dmsDocument.getParentID());
    request.setAttribute("location", path);
    request.setAttribute("attachmentList",attachmentList);
    
    this.setEmailContent(request,dmsDocument);
  }

  
  /**
   * this function is to getting the supporting documents of compound document.
   * @param ID                          ID of Compound document
   * @param rootID                      RootID of Compound document
   * @param request                     HttpServletRequest
   * @param form                        ActionForm of struts
   */
  public void selectChildList(Integer ID, Integer rootID,HttpServletRequest request,ActionForm form) throws ApplicationException{
    MaintDmsEmailDocumentForm maintForm = (MaintDmsEmailDocumentForm) form;
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    List documentList = new ArrayList();
    List newDocumentList=new ArrayList();
    int startOffset = TextUtility.parseInteger(maintForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(maintForm.getPageOffset());
    int rowLoopCnt = 0;
    try{
      documentList = docRetrievalManager.getDocumentListByParentIDRootID(ID, rootID);
    } catch (Exception ee) {
      log.error(ee,ee);
    }
    //reset the value of dmsDocument for paging.
    if (!Utility.isEmpty(documentList)){
      if(documentList.size()-startOffset>pageSize){
        for(int i=startOffset-1;i<startOffset-1+pageSize;i++){
          DmsDocument dmsDocument=(DmsDocument)documentList.get(i);
          dmsDocument.setRowNum(i+1);
          dmsDocument.setRecordCount(documentList.size());
          dmsDocument.setHasRelationship(docRetrievalManager.hasRelationship(dmsDocument.getID(),""));
          newDocumentList.add(dmsDocument);
        }
      }else{
        for(int i=startOffset-1;i<documentList.size();i++){
          DmsDocument dmsDocument=(DmsDocument)documentList.get(i);
          dmsDocument.setRowNum(i+1);
          dmsDocument.setRecordCount(documentList.size());
          dmsDocument.setHasRelationship(docRetrievalManager.hasRelationship(dmsDocument.getID(),""));
          newDocumentList.add(dmsDocument);    
        }
      }
    }
    
    request.setAttribute(sListName, newDocumentList);
    
    List resultList = (List)request.getAttribute(sListName);
    while ( (resultList.size()==0) && (TextUtility.parseInteger(maintForm.getCurStartRowNo())>TextUtility.parseInteger(maintForm.getPageOffset())) ) {
      int prvRowNo = TextUtility.parseInteger(maintForm.getCurStartRowNo())-TextUtility.parseInteger(maintForm.pageOffset);
      maintForm.setCurStartRowNo(TextUtility.formatInteger(prvRowNo));
      selectChildList(ID, rootID, request,form);
    }
  }

  /**
 *  Method deleteListData() - delete the item(s) from listing page
 *
 *  @param      mapping               ActionMapping from struts
 *  @param      form                  ActionForm from struts
 *  @param      request               HttpServletReuqest
 *  @param      respond               HttpServletRespond
 *  @return     void
 *  @throws     ApplicationException  Throws ApplicationException the deleteion failed
 */
  public void deleteListData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    MaintDmsEmailDocumentForm searchForm = (MaintDmsEmailDocumentForm)form;
    String[] idAry = request.getParameterValues("basicSelectedID");

    // String[] idAry = searchForm.getBasicSelectedID();
    Connection conn = null;
    //try {
      conn = this.getConnection(request);
      DocumentOperationManager docOpManager = new DocumentOperationManager(this.getSessionContainer(request), conn);
      DmsDocumentDAObject dmsDocDAO = new DmsDocumentDAObject(this.getSessionContainer(request), conn);

      if (!Utility.isEmpty(idAry)) {
        for (int i = 0; i < idAry.length; i++) {
          DmsDocument dmsDoc = (DmsDocument) dmsDocDAO.getObjectByID(new Integer(idAry[i]));
          docOpManager.deleteDocument(dmsDoc);
        }
      }

      docOpManager.release();
      dmsDocDAO = null;
  }

  /**
   * execute - refresh form data.
   *
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @return
   * @throws ServletException
   */
  public void refreshFormData(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    MaintDmsEmailDocumentForm documentForm = (MaintDmsEmailDocumentForm) form;
    DmsDocument document = (DmsDocument) documentForm.getFormData();
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    
    String docIDStr = documentForm.getID();
    if (Utility.isEmpty(docIDStr)){
      docIDStr = (String)request.getAttribute("documentID");
    }
    if (!Utility.isEmpty(docIDStr)){
     
      Integer docID = new Integer (docIDStr);
      document = docRetrievalManager.getDocument(docID);

      super.refreshFormData(mapping, documentForm, request, response);
      
      if (DmsDocument.COMPOUND_DOC_TYPE.equals(document.getDocumentType())){
        selectChildList(document.getID(), document.getRootID(), request,form);
      }else{
        selectChildList(document.getParentID(), document.getRootID(), request,form);
      } 
    }

    List udfDetailList = docRetrievalManager.getUDFDetailList(TextUtility.parseIntegerObj(documentForm.getUserDefinedFieldID()));
    documentForm.setUdfDetailList(udfDetailList);
    log.debug("======refresh form data ar list size:"+udfDetailList.size());
    String path = (String)request.getAttribute("location");
    if (Utility.isEmpty(path)) {
      path = docRetrievalManager.getLocationPath(TextUtility.parseIntegerObj(documentForm.getParentID()));
    }
    request.setAttribute("location", path);
    document.setUserDefinedFieldID(TextUtility.parseIntegerObj(documentForm.getUserDefinedFieldID()));
    documentForm.setFormData(document);     
    sessionContainer = null;
    conn=null;
    docRetrievalManager.release();
  }
  
  private void setEmailContent(HttpServletRequest request,DmsDocument dmsDocument) throws ApplicationException{
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);  
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);   
    DmsVersion dmsVersion = docRetrievalManager.getTopVersionByDocumentID(dmsDocument.getID());
    DmsContent docContent = docRetrievalManager.getContentByContentID(dmsVersion.getContentID());
      
    InputStream dataStream=docRetrievalManager.getDataInputStreamByDocument(dmsDocument,dmsVersion,docContent);
    request.setAttribute("emailContent",dataStream);
  }
  
  public void updateRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);

    MaintDmsEmailDocumentForm documentForm = (MaintDmsEmailDocumentForm) form;    
    DmsDocument document = (DmsDocument) documentForm.getFormData();
    try { 
//      String emailUDFProfileID = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_PROFILE_EMAIL_ID);
//      String emailUDFMailFromID = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_PROFILE_EMAIL_DETAIL_MAILFROM_ID);
      Integer emailUDFMailToID = TextUtility.parseIntegerObj(SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_PROFILE_EMAIL_DETAIL_MAILTO_ID));
      Integer emailUDFCCToID = TextUtility.parseIntegerObj(SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_PROFILE_EMAIL_DETAIL_CCTO_ID));
//      String emailUDFSubjectID = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_PROFILE_EMAIL_DETAIL_SUBJECT_ID);
//      String emailUDFSendDateID = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_PROFILE_EMAIL_DETAIL_MAILSENDDATE_ID);
      //update mailtocc detail
      DmsDocumentDetail mailccToDetail = docRetrievalManager.getDetailObjectByDocIDUDFDetailID(document.getID(),emailUDFCCToID);
      mailccToDetail.setFieldValue(documentForm.getMailCCTo());
      docOperationManager.updateDocumentDetail(mailccToDetail);
      //update mailto detail
      DmsDocumentDetail mailToDetail = docRetrievalManager.getDetailObjectByDocIDUDFDetailID(document.getID(),emailUDFMailToID);
      mailToDetail.setFieldValue(documentForm.getMailTo());
      docOperationManager.updateDocumentDetail(mailToDetail);
       
      DmsDocument newDocument = docOperationManager.updateDocument(document);
      documentForm.setUdfDetailList(newDocument.getUdfDetailList());
      documentForm.setDocumentDetails(newDocument.getDocumentDetails());
      documentForm.setFormData(newDocument, newDocument.getDocumentDetails());
      String path = docRetrievalManager.getLocationPath(TextUtility.parseIntegerObj(parentID));
      request.setAttribute("location", path);

      sessionContainer = null;
      docRetrievalManager.release();
      docOperationManager.release();

    } catch (Exception e) {
        log.error(e, e);
    } finally {
      conn = null;
    }    
  }
  
}
